<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Organization_Model extends CI_Model {
	
	public function get_organization_by_id($id) {
		$query = "SELECT * FROM smb_organizations WHERE id = ?";
		$result = $this->db->query($query, array($id));
		if ($result->num_rows() == 1) {
			return $result->row();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function count_organization($username) {
		$query = "SELECT COUNT(*) AS sum FROM smb_organizations WHERE username = ?";
		$result = $this->db->query($query, array($username));
		if ($result->num_rows() == 1) {
			return $result->row()->sum;
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function get_organization($username, $offset, $limit) {
		if ($offset == '' || $limit == '') {
			$query = "SELECT * FROM smb_organizations WHERE username = ? ORDER BY year DESC, name ASC";
			$result = $this->db->query($query, array($username));
		} else {
			$query = "SELECT * FROM smb_organizations WHERE username = ? ORDER BY year DESC, name ASC LIMIT ?, ?";
			$result = $this->db->query($query, array($username, intval($offset), intval($limit)));
		}
		if ($result->num_rows() > 0) {
			return $result->result();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function add_organization($username, $name, $year, $position) {
		$query = "INSERT INTO smb_organizations (id, username, name, year, position) VALUES (UUID(), ?, ?, ?, ?)";
		
		$this->db->trans_start();
		$this->db->query($query, array($username, $name, $year, $position));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	public function edit_organization($id, $name, $year, $position) {
		$query = "UPDATE smb_organizations SET name = ?, year = ?, position = ? WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($name, $year, $position, $id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	public function delete_organization($id) {
		$query = "DELETE FROM smb_organizations WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
}